package io.github.wanggit.antcms.server.web.utils;

import io.github.wanggit.antcms.server.dto.CatalogDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class TreeNodeUtil {

    private final List<CatalogDTO> nodes;

    public TreeNodeUtil(List<CatalogDTO> nodes) {
        this.nodes = nodes;
    }

    /**
     * 把无序的列表整理成树
     *
     * @return
     */
    public List<CatalogDTO> toTree() {
        List<CatalogDTO> firstLevelNodes =
                nodes.stream().filter(it -> null == it.getParentId()).collect(Collectors.toList());
        nodes.removeAll(firstLevelNodes);
        firstLevelNodes.forEach(this::fixRelation);
        return firstLevelNodes;
    }

    private void fixRelation(CatalogDTO parentNode) {
        nodes.forEach(
                node -> {
                    if (null != node.getParentId()
                            && Objects.equals(node.getParentId(), parentNode.getId())) {
                        node.setParentNode(parentNode);
                        parentNode.addChild(node);
                        parentNode.setLeaf(false);
                        node.setLv((short) (parentNode.getLv() + 1));
                    }
                });
        nodes.removeAll(parentNode.getChildren());
        if (!parentNode.getChildren().isEmpty()) {
            parentNode.getChildren().forEach(this::fixRelation);
        }
    }

    /**
     * 前序遍历，拉平到列表
     *
     * @return
     */
    public List<CatalogDTO> treePreOrders() {
        List<CatalogDTO> catalogDTOS = toTree();
        List<CatalogDTO> nodes = new ArrayList<>();
        catalogDTOS.forEach(root -> internalTreePreOrders(nodes, root));
        return nodes;
    }

    private void internalTreePreOrders(List<CatalogDTO> nodes, CatalogDTO root) {
        nodes.add(root);
        root.getChildren().forEach(it -> internalTreePreOrders(nodes, it));
    }
}
